package com.qingyun.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qingyun.reggie.common.R;
import com.qingyun.reggie.entity.User;
import com.qingyun.reggie.service.UserSerivce;
import com.qingyun.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserSerivce userSerivce;

    @Resource
    private JavaMailSender javaMailSender;

    //读取yml文件中username的值并赋值给form
    @Value("${spring.mail.username}")
    private String from;


    /**
     * 发送邮箱验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> senMsg(@RequestBody User user, HttpSession session){
        String email = user.getEmail();
        if (StringUtils.isNotEmpty(email)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码为{}",code);
            // 构建一个邮件对象
            SimpleMailMessage message = new SimpleMailMessage();
            // 设置邮件发送者
            message.setFrom(from);
            // 设置邮件接收者
            message.setTo(email);
            // 设置邮件的主题
            message.setSubject("登录验证码");
            // 设置邮件的正文


            String text = "[青云共月]您的验证码为：" + code + ",请勿泄露给他人。";
            message.setText(text);
            // 发送邮件
            try {
                javaMailSender.send(message);
                session.setAttribute(email,code);
                return R.success("发送成功");
            } catch (MailException e) {
                e.printStackTrace();
            }

        }

        return R.error("发送失败");
    }


    /**
     * 移动端用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());

        //获取邮箱
        String email = map.get("email").toString();
        //获取验证码
        String code = map.get("code").toString();

        Object codeInSession = session.getAttribute(email);
        //进行验证码的比对
        if (codeInSession!=null&&codeInSession.equals(code)){
            //判断当前邮箱对应的用户是否为新用户，如果是则自动完成注册
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail,email);
            User user = userSerivce.getOne(queryWrapper);
            if (user==null){
                user=new User();
                user.setEmail(email);
                userSerivce.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }

        return R.error("登录失败");
    }


    /**
     * 用户退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request) {
        //清理 session 中的用户 id
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }

}
